package com.weibo.demos.web.Controller;

import com.weibo.demos.web.Service.UserService;
import com.weibo.demos.web.entity.UserVO;
import com.weibo.demos.web.entity.userLoginDTO;
import com.weibo.demos.web.entity.userRegDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v1/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/reg")
    public int addUser(@RequestBody userRegDTO user) {
        log.info("用户注册信息：{}", user);
        return userService.addUser(user);
    }

    /**
     * 用户登录
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public int login(@RequestBody userLoginDTO user, HttpServletRequest request) {
        log.info("用户登录信息：{}", user);

        // 调用服务层进行登录验证，获取完整用户信息
        UserVO userVO = userService.userLogin(user);

        if (userVO != null) {
            if (userVO.getPassword()!=null){
                // 将完整的用户信息存入Session
                HttpSession session = request.getSession();
                session.setAttribute("user", userVO);
            }else {
                return 2;
            }
        } else {
            log.warn("用户登录失败，用户名或密码错误");
            return 3;
        }

        return 1;
    }

    /**
     * 获取当前用户登录状态
     * @param request
     * @return
     */
    @GetMapping("/currentUser")
    public UserVO selectUseLoginStatus(HttpServletRequest request) {
        log.info("获取当前用户登录状态");

        // 从Session中获取用户信息
        HttpSession session = request.getSession(false); // 不创建新Session

        if (session != null) {
            UserVO user = (UserVO) session.getAttribute("user");
            log.info("当前登录用户: {}", user != null ? user.getNickname() : "未登录");
            return user;
        }

        log.info("Session不存在，用户未登录");
        return null;
    }

    @GetMapping("/logout")
    public void logout(HttpServletRequest request){
        //删除session中的用户信息
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute("user");
        }
    }
}